package cn.edu.cqupt.cxcy.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.edu.cqupt.cxcy.dto.IndexImpl;

/**
 * 检查请求的客户端的是否有session或者cookie 自动注册
 * @author Dancer-mno
 * @date 2015年10月11日
 */
@WebFilter("/ChcekCookie")
public class ChcekCookie implements Filter {

	/**
	 * Default constructor. 
	 */
	public ChcekCookie() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession();
		if(session.getAttribute( "user") == null) {
			Cookie[] cookies = null;
			cookies = httpRequest.getCookies();// 获取与该域相关的 Cookies 的数组
			Cookie cookie = null;
			if(cookies != null) {
				List<Object> login = new ArrayList<>();
				for( int i=0; i<cookies.length; i++) {
					cookie = cookies[i];
					String values = cookie.getValue();
					login.add(values);
				}
				if(login.size() == 2) {
					List<Object> user = new ArrayList<>();
					user = new IndexImpl().login(login);
					if(user != null && !user.isEmpty()) {
						session.setAttribute("user", user);
					}
				}
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
